<template>
  <div>
    <Category :scence="scence" />
    <el-card style="margin: 10px 0px">
      <div v-show="scence == 0">
        <el-button
          type="primary"
          icon="plus"
          :disabled="categoryStore.C3Id ? false : true"
          @click="addAttr"
        >
          添加平台属性
        </el-button>
        <el-table border style="margin: 10px 0px" :data="attrData">
          <el-table-column
            label="序号"
            width="80"
            type="index"
            align="center"
          />
          <el-table-column label="属性名称" prop="attrName" width="180" />
          <el-table-column label="属性值名称">
            <template #default="scope">
              <el-tag
                class="ml-2"
                type="success"
                v-for="item in scope.row.attrValueList"
                :key="item.id"
                style="margin: 0px 5px"
              >
                {{ item.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template #="{ row, $index }">
              <el-button
                type="primary"
                size="small"
                icon="Edit"
                @click="editAttr(row)"
              />
              <el-popconfirm
                width="200px"
                :title="`确定要删除属性${row.attrName}?`"
                @confirm="removeAttr(row.id)"
              >
                <template #reference>
                  <el-button type="danger" size="small" icon="Delete" />
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="scence == 1">
        <el-form :inline="true">
          <el-form-item label="属性名称">
            <el-input
              placeholder="请输入属性名称"
              v-model="attrParams.attrName"
            />
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          icon="plus"
          @click="addAttrParams"
          :disabled="attrParams.attrName ? false : true"
        >
          添加属性值
        </el-button>
        <el-button type="primary" @click="cancel">取消</el-button>
        <el-table
          border
          style="margin: 10px 0px"
          :data="attrParams.attrValueList"
        >
          <el-table-column label="序号" type="index" width="80" />
          <el-table-column label="属性值名称">
            <template #="{ row, $index }">
              <el-input
                :ref="(vc: any) => (inputArr[$index] = vc)"
                @blur="changeLookStatus(row, $index)"
                v-if="row.isEdit"
                placeholder="请输入属性值名称"
                v-model="row.valueName"
              />
              <div @click="changeEditStatus(row, $index)" v-else>
                {{ row.valueName }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="属性值操作">
            <template #="{ row, $index }">
              <el-button
                type="primary"
                size="small"
                icon="delete"
                @click="deleteAttrValue($index)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          @click="saveAttr"
          :disabled="attrParams.attrValueList.length > 0 ? false : true"
        >
          保存
        </el-button>
        <el-button type="primary" @click="cancel">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import useCategoryStore from '@/store/modules/category'
import { GetAttr, AddOrUpdateAttr, DeleteAttr } from '@/api/product/attr'
import type {
  CategoryAttrResponse,
  Attr,
  AttrLabel,
} from '@/api/product/attr/type'
const categoryStore = useCategoryStore()
import { watch, ref, reactive, nextTick, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
//对类型3进行监视，如果有值，则发送请求
watch(
  () => categoryStore.C3Id,
  () => {
    //重置表格数据
    attrData.value = []
    //如果类别3没有，则不发请求
    if (!categoryStore.C3Id) {
      return
    }
    //请求属性列表
    getAttrList()
  },
)
//接收属性列表数据
let attrData = ref<Attr[]>([])
//添加/显示开关
let scence = ref<number>(0)
//接收新增属性数据
let attrParams = reactive<Attr>({
  attrName: '', //新增属性的名称
  attrValueList: [], //新增的属性值列表
  categoryId: 0, //三级分类的ID
  categoryLevel: 3, //代表是三级分类
})
//存储所有的element-input对象
let inputArr = ref<any>([])

//获取属性列表
const getAttrList = async () => {
  let { C1Id, C2Id, C3Id } = categoryStore
  const result: CategoryAttrResponse = await GetAttr(C1Id, C2Id, C3Id)
  attrData.value = result.data
}

//添加属性回调
const addAttr = () => {
  //重置数据
  Object.assign(attrParams, {
    attrName: '', //新增属性的名称
    attrValueList: [], //新增的属性值列表
    categoryId: categoryStore.C3Id, //三级分类的ID
    categoryLevel: 3, //代表是三级分类
  })
  //显示属性添加界面
  scence.value = 1
}

//修改属性回调
const editAttr = (row: Attr) => {
  //显示属性添加界面
  scence.value = 1
  //将修改的值赋值给attrParams对象
  //Object.assign(attrParams, row)
  //不能使用上句，因为上句使用的是浅拷贝，只是拷贝的地址，修改attrParams对象也会对row对象造成影响
  //造成的后果是，如果修改后没有点保存，而是点的取消，则返回时显示数据不正确
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)))
}

//属性值取消回调
const cancel = () => {
  scence.value = 0
}

//添加属性值回调
const addAttrParams = () => {
  attrParams.attrValueList.push({ valueName: '', isEdit: true })
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length - 1].focus()
  })
}

//保存属性回调
const saveAttr = async () => {
  const result: any = await AddOrUpdateAttr(attrParams)
  if (result.code == 200) {
    ElMessage.success(`${attrParams.id ? '添加' : '修改'}成功`)
    scence.value = 0
    getAttrList()
  } else {
    ElMessage.error(`${attrParams.id ? '添加' : '修改'}失败`)
  }
}

//变更成查看状态
const changeLookStatus = (row: AttrLabel, $index: number) => {
  //判断属性值不能为空
  if (row.valueName.trim().length <= 0) {
    //删除调用对象为空的元素
    attrParams.attrValueList.splice($index, 1)
    //提示错误信息
    ElMessage.error('属性值内容不能为空!')
    return
  }
  //判断输入的值不能重复
  attrParams.attrValueList.forEach((item) => {
    if (item != row) {
      if (item.valueName == row.valueName) {
        //删除重复的元素
        attrParams.attrValueList.splice($index, 1)
        ElMessage.error('属性值不能重复')
        return
      }
    }
  })
  //将输入框状态变为查看状态
  row.isEdit = false
}
//变更成编辑状态
const changeEditStatus = (row: AttrLabel, index: any) => {
  //变更成编辑状态
  row.isEdit = true
  //nextTick:当响应式对象完成更新后，获取相应的DOM元素
  nextTick(() => {
    //设置当前Input自动获取焦点
    inputArr.value[index].focus()
  })
}

//删除对应的属性值
const deleteAttrValue = (index: number) => {
  attrParams.attrValueList.splice(index, 1)
}
//删除对应的属性
const removeAttr = async (id: number) => {
  let result: any = await DeleteAttr(id)
  if (result.code == 200) {
    ElMessage.success('删除成功!')
    getAttrList()
  } else {
    ElMessage.error('删除失败!')
  }
}

//组件消毁清除类型信息
onBeforeUnmount(() => {
  categoryStore.$reset()
})
</script>

<style scoped></style>
